package fr.efrei.tradesys.struts.actions.currencies;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionSupport;

import fr.efrei.tradesys.hibernate.beans.Rate;
import fr.efrei.tradesys.hibernate.factory.DaoFactory;

public class AccelerateTimeAction extends ActionSupport
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1L;
	private static Log				LOGGER						= LogFactory
																									.getLog(AccelerateTimeAction.class);
	private int								nbDays;

	public String execute() throws Exception
	{
		LOGGER.info("Execution of " + this.getClass().getName());
		Random r = new Random(System.currentTimeMillis());
		double newAsk;
		double newBid;
		double newEvolution;
		Calendar c;
		Date newRateDate;
		for (int i = 0; i < nbDays; ++i)
		{
			for (Rate oldRate : DaoFactory.getInstance().getRateDao().getLastRates())
			{
				newEvolution = r.nextDouble() * 1.2 - 0.6 + oldRate.getEvolution() / 4;
				newAsk = oldRate.getAsk() * ((newEvolution / 100) + 1);
				newBid = 0.9997 * newAsk;
				c = Calendar.getInstance();
				c.setTime(oldRate.getRateDate());
				if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
				{
					c.add(Calendar.DATE, 3);
				}
				else
				{
					c.add(Calendar.DATE, 1);
				}
				newRateDate = c.getTime();
				Rate newRate = new Rate(newAsk, newBid, newEvolution, newRateDate);
				newRate.setCurrency1(oldRate.getCurrency1());
				newRate.setCurrency2(oldRate.getCurrency2());
				DaoFactory.getInstance().getRateDao().addRate(newRate);
			}
		}
		return SUCCESS;
	}

	public int getNbDays()
	{
		return nbDays;
	}

	public void setNbDays(int nbDays)
	{
		this.nbDays = nbDays;
	}

}
